<?php
/**
 * @version 0.8.3 2010-10-07
 * @package Joomla
 * @subpackage LeagueResults
 * @copyright (C)  2008, 2009, 2010 Henryk Drozd
 * @license GNU/GPL, see LICENSE.php
 * LeagueResults is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License 2
 * as published by the Free Software Foundation.

 * LeagueResults is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.




 */
defined('_JEXEC') or die('Restricted access');
jimport('joomla.application.component.model');


class lrModelSampledata extends JModel
{
function __construct()
	{
		parent::__construct();
		
		if ($this->_check()) {
			JError::raiseWarning('SOME ERROR CODE', JText::_('DATA ALREADY INSTALLED'));
			return false;
		}
	}
function loaddata()
	{	
		$scriptfile 	= JPATH_COMPONENT_ADMINISTRATOR.DS.'assets'.DS.'sampledata.sql';
		//load sql file
		if( !($buffer = file_get_contents($scriptfile)) )
		{
			return false;
		}
		
		//extract queries out of sql file
		$queries = $this->_splitSql($buffer);

		//Process queries
		foreach ($queries as $query)
		{
			$query = trim($query);
			if ($query != '' && $query {0} != '#')
			{
				$this->_db->setQuery($query);
				$this->_db->query();
			}

			}
		return true;
	}

	function _splitsql($sql)
	{
		$sql 		= trim($sql);
		$sql 		= preg_replace("/\n\#[^\n]*/", '', "\n".$sql);
		$buffer 	= array();
		$ret 		= array();
		$in_string 	= false;

		for ($i = 0; $i < strlen($sql) - 1; $i ++) {
			if ($sql[$i] == ";" && !$in_string)
			{
				$ret[] = substr($sql, 0, $i);
				$sql = substr($sql, $i +1);
				$i = 0;
			}

			if ($in_string && ($sql[$i] == $in_string) && $buffer[1] != "\\")
			{
				$in_string = false;
			}
			elseif (!$in_string && ($sql[$i] == '"' || $sql[$i] == "'") && (!isset ($buffer[0]) || $buffer[0] != "\\"))
			{
				$in_string = $sql[$i];
			}
			if (isset ($buffer[1]))
			{
				$buffer[0] = $buffer[1];
			}
			$buffer[1] = $sql[$i];
		}

		if (!empty ($sql))
		{
			$ret[] = $sql;
		}
		return ($ret);
	}
	

	
	function _check()
	{
		$query = 'SELECT id FROM #__lr_tablecontents';
		
		$this->_db->setQuery( $query );
		
		$result = $this->_db->loadResult();
		
		return $result;
	}


}

?>